package com.stox.client.http;

import lombok.Data;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import com.stox.dto.exception.StoxHttpException;
import com.stox.dto.exception.StoxResponseException;
import com.stox.dto.web.Response;

@Data
public abstract class AbstractHttpClient {

	@Autowired
	private UrlProvider urlProvider;
	
	@Autowired
	private RestTemplate restTemplate;
	
	public String getRootUrl(){
		return urlProvider.getRoolUrl();
	}

	protected <T> T extract(ResponseEntity<Response<T>> responseEntity){
		if(null != responseEntity){
			if(!HttpStatus.OK.equals(responseEntity.getStatusCode())){
				throw new StoxHttpException(responseEntity.getStatusCode());
			}
			if(null != responseEntity.getBody()){
				Response<T> response = responseEntity.getBody();
				if(!response.isSuccess()){
					throw new StoxResponseException(response);
				}
				return responseEntity.getBody().getPayload();
			}
		}
		return null;
	}
	
}
